import {Inject} from 'plugins'
import config from 'config';

@Inject('$scope', '$state', 'ui.http', 'ui.dialog', 'ui.api')
export default class SettingsList {
	constructor($scope, $state, http, dialog, api) {
		var appScope = $scope.$parent;

	    function getTreeNode() {
	        return appScope.getTreeNode();
	    }

	    var node = getTreeNode();
		var q = $scope.q = {};

		var loadData = $scope.loadData = function(params) {
				var node = getTreeNode();
				if (!node) return;
				params = angular.extend({}, params, {
					cid: node.id
				});
				api.gridLoad({
					name: 'settings', 
					params: params,
					scope: $scope
				});
			};

	    var query = $scope.query = function(resetPage) {
			if (resetPage === false || $scope.gridOptions.paginationCurrentPage == 1) {
				loadData(q);
			} else {
				api.gridReset(null, $scope);
			}
		}

		$scope.add = function() {
			api.form({
				title: '添加数据源', 
				template: require('./views/form.tpl.html'), 
				name: 'settings_add',
				data: {
	                cid: node.id
	            },
			}).then(function() {
				query();
			});
		}
		$scope.edit = function() {
			var id = api.getGridSelectedId($scope);
			api.form({
				title: '修改设置', 
				template: require('./views/form.tpl.html'), 
				name: 'settings_edit',
				resolveWait: http.post({
					name: 'settings_item',
					params: {
						id: id
					}
				})
			}).then(function() {
				query(false);
			});
		}
		$scope.remove = function() {
			var ids = api.getGridSelectedIds($scope);
			dialog.confirm('确定要移除选中的设置？').result.then(function(r) {
				if (r) {
					http.post({
						name: 'settings_remove',
						params: {
							ids: ids
						},
						success: function() {
							query(false);
						}
					})
				}
			});
		}

		$scope.gridOptions = {
			paginationCurrentPage: api.page.pageNumber,
			paginationPageSize: api.page.pageSize,
			useExternalPagination: true,
			columns: [{
				name: '序号',
				width: 50,
				// field: 'id',
				cellTemplate: '<div class="x-grid-inner">{{(grid.options.paginationCurrentPage - 1) * grid.options.paginationPageSize + (index + 1)}}</div>'
			}, {
				name: 'key值',
				width: 200,
				field: 'sysKey',
				align: 'left'
			}, {
				name: 'value值',
				width: 300,
				field: 'sysValue',
	            align: 'left'
			}, {
				name: '描述',
				field: 'remark',
	            align: 'left'
			}],
			onRegisterApi: function(api) {
				$scope.api = api;
				api.pagination && api.pagination.on.paginationChanged($scope, function(newPage, pageSize) {
					query(false);
				});
			}
		};

		$scope.hasSelected = function() {
			return api.hasGridSelected($scope);
		}
		$scope.hasSelectedRecords = function() {
			return api.hasGridSelectedRecords($scope);
		}

		query();
	}
}